/**
 * @author jiagnqifan
 * @since 2016-03-31
 */

var Build = require('../../../models').Build;
var BuildProxy = require('../../../proxy').Build;
var logger = require('log4js').getLogger();
var EventProxy = require('eventproxy');
var build_types = require('./build_types');
var _ = require('lodash');

//check progress
function check(){
  //logger.info('build monitor check.');
  var ep = new EventProxy();
  ep.fail(function(err){
    logger.error(err);
  });
  BuildProxy.getBuilding(function(err, data){
    if(err){
      ep.throw(err);
    }
    if(data && data.length){
      logger.info('building length:'+data.length);
      _.forEach(data, checkOne);
    }
    //if(data){
    //  _.forEach(data, checkOne);
    //}
  });

}

function checkOne(build, callback){
  logger.info('check:' + build._id);
  if(build.config){
      var type = build.config.type;
      var policy = build_types.find(type);
      if( !policy ){
          logger.error('illegal type:' + type);
          if('funciton' === callback){
              callback('can not find type:'+type);
          }
          return;
      }
      policy.tryComplete(build, callback);
  }
}

var DELAY = 2000;
var interval = null;
exports.start = function(){
  logger.info('build monitor start.');
  interval = setInterval(check, DELAY);
}
exports.stop = function(){
  logger.info('build monitor stop.');
  clearInterval(interval);
  interval = null;
}
